package rss.builder 
{
	import rss.enums.RssEnum;
	import rss.errors.RssFeedError;
	import rss.IRssEntryBuilder;
	import rss.IRssEntryModel;
	import rss.IRssFeedBuilder;
	import rss.IRssFeedModel;
	import rss.models.RssFeedModel;
	import common.utilities.Convert;
	/**
	 * Constructs an feed model from an <rss /> XML node. The feed is 
	 * (marginally) validated during the construction process to ensure
	 * validity. Once the feed model has been constructed the original
	 * XML can be discarded.
	 * 
	 * @author Luke Van In
	 */
	public class XmlRssFeedBuilder implements IRssFeedBuilder
	{
		
		// private var
		private var _xml:XML;
		
		
		/**
		 * Constructor
		 * 
		 * @param	xml
		 */
		public function XmlRssFeedBuilder(xml:XML) 
		{
			this._xml = xml;
		}
		
		
		
		/* INTERFACE rss.IRssFeedBuilder */
		
		/**
		 * 
		 * @return
		 * @throws		RssFeedError.UNSUPPORTED_VERSION		Only version 2.0 is supported
		 * @throws		RssFeedError.MALFORMED_XML				XML must conform to the RSS 2.0 specification
		 */
		public function buildFeed():IRssFeedModel 
		{
			// parse and verify XML
			if (this._xml.@version.toString() != "2.0")
				throw new RssFeedError(RssFeedError.UNSUPPORTED_VERSION);
				
			if (this._xml.channel[0] == undefined)
				throw new RssFeedError(RssFeedError.MALFORMED_XML);
				
			var channelXml:XML = this._xml.channel[0];
			
			var ns:Namespace = RssEnum.ATOM_NAMESPACE;
			
			// create and return feed
			var feed:IRssFeedModel = new RssFeedModel(
				channelXml.title.toString(), 
				// TODO: parse links channelXml.ns::link.toString(), 
				channelXml.description.toString(), 
				channelXml.language.toString(), 
				Convert.stringToDate(channelXml.pubDate.toString()), 
				Convert.stringToDate(channelXml.lastBuildDate.toString()), 
				channelXml.generator.toString(), 
				Convert.stringToInt(channelXml.generator.toString), 
				this.buildEntries(channelXml));
			
			return feed;
		}
		
		
		
		/**
		 * Constructs and returns a vector of RSS entries from a collection of
		 * RSS <item /> nodes.
		 * 
		 * @return
		 */
		private function buildEntries(xml:XML):Vector.<IRssEntryModel>
		{
			var entries:Vector.<IRssEntryModel> = new Vector.<IRssEntryModel>();
			
			for each (var itemXml:XML in xml.item)
			{
				var entry:IRssEntryModel = this.buildEntry(itemXml);
				
				entries.push(entry);
			}
						
			return entries;
		}
				
		
		
		/**
		 * Constructs and returns an instance of a feed entry model from an
		 * RSS <item /> node.
		 * 
		 * @param	xml
		 * @return
		 */
		private function buildEntry(xml:XML):IRssEntryModel
		{
			var builder:IRssEntryBuilder = new XmlRssEntryBuilder(xml);
			
			var entry:IRssEntryModel = builder.buildEntry();
			
			return entry;
		}
		
		
		
		
		
		/**
		 * 
		 */
		public function dispose():void
		{
			
		}
		
		

		
		
	}

}